package top.milkbox.core;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * druid工具类
 *
 * @author milkbox
 */
public class UtilsJDBCDruid {
    // 定义连接池对象
    private static DataSource dataSource = null;

    // 获取当前类名
    private static final String CLASSNAME = UtilsJDBCDruid.class.getSimpleName();

    static {
        try {
            // 获取配置文件
            ClassLoader classLoader = UtilsJDBCDruid.class.getClassLoader(); // 获取当前的类加载器
            InputStream resourceAsStream = classLoader.getResourceAsStream("druid.properties"); // 获取指定文件的字字符流
            // 加载配置文件
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            log(properties.getProperty("url"));
            // 创建连接池对象
            dataSource = new DruidDataSourceFactory().createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 从连接池中获取一个连接
     *
     * @return 返回一个Connection对象
     * @throws SQLException 连接异常
     */
    public static Connection getConnection() throws SQLException {
        Connection connection = dataSource.getConnection();
        log(connection.toString());
        return connection;
    }

    /**
     * 获取连接池对象
     *
     * @return 返回连接池对象
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 释放资源
     *
     * @param resultSet  结果集
     * @param statement  SQL执行
     * @param connection 连接
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        log("释放资源，归还连接...");
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                // 将连接归还给连接池
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     *
     * @param statement  SQL执行
     * @param connection 连接
     */
    public static void close(Statement statement, Connection connection) {
        close(null, statement, connection);
    }

    /**
     * 当前类打印的日志
     *
     * @param message 要打印的内容
     */
    private static void log(String message) {
        System.out.println("log from " + CLASSNAME + ": " + message);
    }
}
